var tree;
var toPage;
$(function () {
    roleValidation();
    /* 角色访问权限列表 */
    layui.use('tree', function () {
        showLoading(LOADING);
        tree = layui.tree;
        getJson("/sys/permission/tree", null, 'GET', function (data) {
            if (data['code'] == 200) {
                let list = [];
                list.push(data['payload']['data']);
                //渲染
                var inst1 = tree.render({
                    elem: '#userAuthorityTree',
                    showCheckbox: true,//是否显示复选框
                    data: list,
                    id: 'treeEle'
                });
                hideLoading();
            } else {
                var inst1 = tree.render({
                    elem: '#userAuthorityTree',
                    showCheckbox: true,//是否显示复选框
                    data: [],
                    id: 'treeEle'
                });
                hideLoading();

            }
            getRoleList();
        })
    });
});

function roleValidation() {
    $('#addInfoForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'fa fa-check',

            validating: 'fa fa-sync-alt'
        },
        fields: {
            displayName: {
                validators: {
                    notEmpty: {
                        message: '角色名不能为空'
                    },
                    stringLength: {
                        min: 1,
                        max: 50,
                    }
                }
            }, type: {
                validators: {
                    notEmpty: {
                        message: '请选择可见范围'
                    },
                    callback: {
                        message: '请选择可见范围',
                        callback: function (value, validator) {
                            if (!getSelectValue($('#type'))) {
                                return false;
                            } else {
                                return true;
                            }
                        }
                    }
                }
            }, expire: {
                validators: {
                    notEmpty: {
                        message: '请选择有效期'
                    },
                }
            }, desc: {
                validators: {
                    notEmpty: {
                        message: '备注不能为空'
                    },
                }
            },
        }
    }).on('success.form.bv', function (e) {
        //防止表单提交
        e.preventDefault();
        //获取表单实例
        var $form = $(e.target);
        //获取BootstrapValidator实例
        jQuery.support.cors = true;
        var bv = $form.data('bootstrapValidator');
        let roleId = $('#validationCustom00').val();
        let roleName = $('#validationCustom01').val();
        let desc = $('#validationCustom02').val();
        let type = getSelectValue($('#type'));
        let expire = $('#validationCustom03').val();
        let permissionList = getTreeChecked(tree.getChecked('treeEle'));
        ////使用Ajax提交表单数据
        getJson("/sys/role/save", {
            id: roleId,
            roleName: roleName,
            desc: desc,
            type: type,
            expire: expire,
            permissionList: permissionList.length == 0 ? null : permissionList
        }, 'GET', function (data) {
            $('#addInfoModal').modal('hide');
            getRoleList(toPage);
            myAlert('提示', data['message']);
        });
    }).on('error.form.bv', function (e) { //点击提交验证失败之后
        $('[type="submit"]').removeAttr("disabled");
    });
}

$('#addInfoModal').on('hidden.bs.modal', function () {
    let form = $('#addInfoForm');
    form.data('bootstrapValidator').destroy();
    form.data('bootstrapValidator', null);
    roleValidation();
    form[0].reset();//清空表单
    resetForm(form);
});

function getRoleList(_pageIndex) {
    showLoading(LOADING);
    let searchValue = $('#searchValue').val();
    let pageIndex = _pageIndex ? _pageIndex : '1';
    toPage = pageIndex;
    getJson('/sys/role/list', {
        searchValue: searchValue,
        pageIndex: pageIndex,
        pageSize: 10
    }, 'GET', function (data) {

        if (data['code'] == 200) {
            $('#addRole').show();
            let payload = data['payload'];
            setPage('#page', pageIndex, payload['pages'], payload['total'], function (num) {
                getRoleList(num);
            });
            let idx = 1;
            for (let item of payload['data']) {
                item['order'] = idx++;
            }
            buildTable('#roleList', titleList, titleLabel, payload['data'], function (ele, label, item) {
                switch (label) {
                    case 'type':
                        $(ele).text(item[label] == 0 ? '系统' : '银行');
                        break;
                    case 'expire':
                        $(ele).text(item[label] == 0 ? '永久' : item[label] + '天');
                        break;
                    case 'opera':
                        if (sysRoleOpera) {
                            let edit = createElement('a', ele);
                            $(edit).addClass('font-p24');
                            let del = createElement('a', ele);
                            $(del).addClass('font-p24');
                            $(del).addClass('delete-option-btn');
                            $(del).addClass('ml-2');
                            let editIcon = createElement('i', edit);
                            $(editIcon).addClass('iconfont');
                            $(editIcon).addClass('icon-bianji-');
                            let delIcon = createElement('i', del);
                            $(delIcon).addClass('iconfont');
                            $(delIcon).addClass('icon-shanchuicon');
                            if (item['readonly'] != 1) {
                                $(edit).attr('href', '##');
                                $(edit).click(function () {
                                    editInfo(this, item['id']);
                                });
                                $(del).attr('href', '##');
                                $(del).click(function () {
                                    delRole(item['id'], item['roleName']);
                                });
                            }
                        }
                        break;
                }
            })
            hideLoading();
        } else {
            setPage($('#page'), pageIndex, 0, 0);
            myAlert('提示', data['message']);
            hideLoading();
        }
    })
}

/*添加*/
function addInfo() {
    resetForm($('#addInfoForm'));
    tree.reload('treeEle');
    $('#modal_title').text('添加角色');
    $('#addInfoModal').modal('show');
}

function getRoleInfo(roleId) {
    getJson("/sys/role/info", {
        roleId: roleId
    }, 'GET', function (data) {
        if (data['code'] == 200) {
            let roleInfo = data['payload']['data'];
            $('#validationCustom00').val(roleInfo['id']);
            $('#validationCustom01').val(roleInfo['roleName']);
            $('#validationCustom02').val(roleInfo['desc']);
            $('#validationCustom03').val(roleInfo['expire']);
            let permissionSet = [];
            for (let item of roleInfo['permissionSet']) {
                permissionSet.push(item['id']);
            }
            tree.setChecked('treeEle', permissionSet)
        }
    })
}

/*修改信息*/
function editInfo(e, roleId) {
    tree.reload('treeEle');
    $('#modal_title').text('修改角色信息');
    getRoleInfo(roleId);
    $('#addInfoModal').modal('show');
}

function delRole(roleId, roleName) {
    myConfirm('警告', '确认删除角色[' + roleName + ']', function (result) {
        if (result) {
            getJson('/sys/role/del', {
                id: roleId
            }, 'GET', function (data) {
                if (data['code'] == 200) {
                    getRoleList(toPage);
                }
                myAlert('提示', data['message']);
            })
        }
    });
}


function getTreeChecked(tree) {
    let arr = [];
    for (let item of tree) {
        if (item['type'] == true) {
            arr.push(item['id']);
        }
        if (item['children'].length > 0) {
            arr.push(...getTreeChecked(item['children']))
        }
    }
    return arr;
}
